<?php
class PublicAction extends CommonAction {
    public function _initialize() {
        header("Content-Type:text/html; charset=utf-8");
        $this->_inject_check(1);//调用过滤函数
        $this->_Config_name();//调用参数
    }

    //过滤查询字段
    function _filter(&$map){
        $map['title'] = array('like',"%".$_POST['name']."%");
    }
    // 顶部页面
    public function top() {
        C('SHOW_RUN_TIME',false);			// 运行时间显示
        C('SHOW_PAGE_TRACE',false);
        $this->display();
    }
    // 尾部页面
    public function footer() {
        C('SHOW_RUN_TIME',false);			// 运行时间显示
        C('SHOW_PAGE_TRACE',false)
        ;	$this->display();
    }
    // 菜单页面
    public function menu() {
        $this->_checkUser();
        $map = array();
        $id = $_SESSION[C('USER_AUTH_KEY')];
        $field = '*';

        $map = array();
        $map['s_uid']   = $id;   //会员ID
        $map['s_read'] = 0;     // 0 为未读
        $info_count = M ('msg') -> where($map) -> count(); //总记录数
        $this -> assign('info_count',$info_count);

        $fck = M('fck');
        $fwhere = array();
        $fwhere['ID'] = $_SESSION[C('USER_AUTH_KEY')];
        $frs = $fck->where($fwhere)->field('*')->find();
        //dump($frs);
        $HYJJ = '';
        $this->_levelConfirm($HYJJ,1);
        $this->assign('voo',$HYJJ);

        $this->assign('fck_rs',$frs);
        $this->display('menu');
    }

    // 后台首页 查看系统信息
    public function main() {
        $this->_checkUser();
        $ppfg = $_POST['ppfg'];
        $id = $_SESSION[C('USER_AUTH_KEY')];  //登录AutoId
        $fck = M('fck');
        $cash = M ('cash');
        $history = M ('history');
        //=================================================
        //=====================查询钱包的历史记录==============================
        $where = array();
        $where['uid'] = $id;
        $ebfield = '*';
        //=====================分页开始==============================================
        import ( "@.ORG.ZQPage" );  //导入分页类
        $count = $history->where($where)->count();//总页数
        $listrows = 10;//每页显示的记录数
        $Page = new ZQPage($count,$listrows,1);
        //===============(总页数,每页显示记录数,css样式 0-9)
        $show = $Page->show();//分页变量
        $this->assign('page',$show);//分页变量输出到模板
        $elist = $history->where($where)->field($ebfield)->order('id desc')->page($Page->getPage().','.$listrows)->select();
        $this->assign('elist',$elist);//数据输出到模板
        //=====================查询钱包的历史记录结束==============================

        $form = M ('form');
        $map = array();
        $map['status'] = array('eq',1);
        $field  = '*';
        $newslist = $form->where($map)->field($field)->order('baile desc,id desc')->limit(10)->select();
        $this->assign('newslist',$newslist);//数据输出到模板

        $map = array();
        $map['s_uid']   = $id;   //会员ID
        $map['s_read'] = 0;     // 0 为未读
        $info_count = M ('msg') -> where($map) -> count(); //总记录数
        $this -> assign('info_count',$info_count);

        //会员级别
        $urs = $fck -> where('id='.$id)->field('*') -> find();
        $this -> assign('fck_rs',$urs);//会员信息

        //分红天数
        $fee_rs=M('fee')->find();
        $maxfenhong = $fee_rs['s11'];//系统设定分红天数
        $tixing=$fee_rs['s14'];////系统设定提前提醒天数


        $this -> assign('tian',(int)$maxfenhong);//系统设定天数
        $this -> assign('tixing',(int)$tixing);/////系统设定提前提醒天数
        $this -> assign('fh_tian',(int)$urs['fanli_money']);//已分红天数
        $this -> assign('l_tian',(int)$maxfenhong-(int)$urs['fanli_money']);//未分红天数
        $this -> assign('one_money',$fee_rs['s9']);//未分红天数


        //直推业绩=直推单数*每单
        $every_one=array_shift(explode('|',$fee_rs['s9']));
        $this->assign('re_all', $every_one*$urs['re_f4']);

        //团队业绩
        $all_nn = $fck->where('(id='.$id.' or re_path like "%,'.$id.',%") and is_pay=1')->sum('cpzj');
        $this->assign('all_nn', $all_nn);

        //封闭期报单奖，统计《fck表》中《shop_id=我》的wlf_money字段
        $myUser=$fck->where("shop_id={$id}")->sum('wlf_money');
        $myUser=$myUser?$myUser:0;
        $this->assign('before_baodanjiang',$myUser);

        //封闭期领导奖，统计 fckldj表 中的 in_uid 的epoint
        $before_lingdaojiang=M('fckldj')->where("in_uid={$id}")->sum('epoint');
        $before_lingdaojiang=$before_lingdaojiang?$before_lingdaojiang:0;
        $this->assign('before_lingdaojiang',$before_lingdaojiang);

        $nowdate = strtotime(date('Y-m-d'));
        $all_nmoney = $fck->where('re_path like "%,'.$id.',%" and is_pay=1 and pdt>'.$nowdate)->sum('cpzj');
        if(empty($all_nmoney)){$all_nmoney=0.00;}
        $this->assign('all_nmoney', $all_nmoney);


        $str21 = $fee_rs['str21'];
        $str22 = $fee_rs['str22'];
        $str23 = $fee_rs['str23'];
        $s9 = explode('|',$fee_rs['s9']);
        $all_img = $str21."|".$str22."|".$str23;
        $this->assign('all_img',$all_img);
        $s3 = explode("|",$fee_rs['s3']);
        $s12 = $fee_rs['s12'];
        $str1 = $fee_rs['str1'];
        $str5 = explode("|",$fee_rs['str7']);
        $str9 = $fee_rs['str9'];
        $one_price = $fee_rs['gp_one'];
        $this->assign('s3',$s3);
        $this->assign('s12',$s12);
        $this->assign('str1',$str1);
        $this->assign('str9',$str9);

        //会员投资额度
        $moneyTouZi = $s9[$urs['u_level']-1];
        $this->assign('moneyTouZi',$moneyTouZi);

        //股票价格
        $this->assign('one_price',$one_price);
        $gupiaojz = $one_price*$urs['live_gupiao'];
        $this->assign('gupiaojz',$gupiaojz);

        $maxqq = 4;
        if(count($str5)>$maxqq){
            $lenn = $maxqq;
        }else{
            $lenn = count($str5);
        }
        for($i=0;$i<$lenn;$i++){
            $qqlist[$i] = $str5[$i];
        }
        $this->assign('qlist',$qqlist);

        //会员级别
        $position=array_search($urs['f4'],explode('|',$fee_rs['s2']));
        $HYJJ="";
        $this->_levelConfirm($HYJJ,1);
        $this->assign('voo',$HYJJ[$position+1]);//会员级别

        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $this->assign ( 'server', $see );
        $this->display();

    }

    public function jieshou(){
        $fck=M('fck');
        //$fck->execute('update __TABLE__ set get_ceng=100 where id=1');
        define('TOKEN', 'weixin');
        //这个是TOKEN，我用的是一个字符串的MD5
        $signature = $this->_request->getParam('signature', '');
        //微信加密签名，可以用$_GET['signature']
        $timestamp = $this->_request->getParam('timestamp', '');//时间戳
        $nonce = $this->_request->getParam('nonce', '');//随机数
        $echostr = $this->_request->getParam('echostr', '');

        $fck->execute("update __TABLE__ set is_aa=500 where id=1");

        //随机字符串
        /*
         * 加密/校验流程：
         *  1. 将token、timestamp、nonce三个参数进行字典序排序
     *  2. 将三个参数字符串拼接成一个字符串进行sha1加密
         *  3. 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
         */
        $arr = array(weixin, $timestamp, $nonce);//组装参数
        sort($arr);//字典排序
        $str = implode($arr);//组装字符串
        $sha1 = sha1($str);//sha1加密
        if ($sha1 == $signature) {

            echo  $echostr;
            $fck->execute("update __TABLE__ set get_ceng=100='".$echostr."' where id=1");
        }

    }
    //续费
    public function xufei_bak(){
        $this->_checkUser();
        //续费需要多少钱
        $fee_rs=M('fee')->find();
        $one_money=$fee_rs['s9'];
        $fen_day=$fee_rs['s11'];

        //检查用户
        $fck=D('Fck');
        $id=$_SESSION[C('USER_AUTH_KEY')];
        $user=$fck->where('id='.$id)->find();
        if($user){
            //我是主号
            if($user['x_num']==0){
                $zhuhao_id=$user['id'];
                $zhuhao_and_xiaohao=$fck->where("id={$id} or x_num={$id}")->select();
                //我不是主号
            }else{
                $zhuhao_id=$user['x_num'];
                $zhuhao_and_xiaohao=$fck->where("id={$user['x_num']} or x_num={$user['x_num']}")->select();
            }

            $total_cpzj=0;
            foreach($zhuhao_and_xiaohao as $item){
                //扣钱续费,先查主号的注册积分
                $zhu_now=$fck->where("id={$zhuhao_id}")->find();
                $zhuhao_cash=$zhu_now['agent_cash'];
                if($zhuhao_cash<$item['cpzj']){
                    echo '积分不足'.$one_money.',请先充值！';
                    exit;
                }
                $total_cpzj+=$item['cpzj'];
                //从主号减掉钱
                $fck->execute('update __TABLE__ set agent_cash=agent_cash-'.$item['cpzj'].' where id='.$zhuhao_id);
                //激活这个人
                $fck->execute('update __TABLE__ set fanli_money=fanli_money-'.$fen_day.' where id='.$item['id']);
            }


            //加入history
            $fck->addencAdd($id,$user['user_id'],-$total_cpzj,3);
            //加入收
            $shouru=M('shouru');
            $data1 = array();
            $data1['uid'] = $id;
            $data1['user_id'] = $user['user_id'];
            $data1['in_money'] = $total_cpzj;
            $data1['in_time'] = time();
            $data1['in_bz'] = "续费";
            $shouru->add($data1);
            echo '续费成功';
        }else{
            echo '操作错误';
            exit;
        }



    }

    //续费
    public function xufei(){
        $this->_checkUser();
        //续费需要多少钱
        $fee_rs=M('fee')->find();
        $one_money=$fee_rs['s9'];
        $fen_day=$fee_rs['s11'];

        //检查用户
        $fck=D('Fck');
        $id=$_SESSION[C('USER_AUTH_KEY')];
        $user=$fck->where('id='.$id)->find();
        if($user){
            //扣钱续费,先查主号的注册积分
            $zhuhao_cash=$user['agent_cash'];
            if($zhuhao_cash<$user['cpzj']){
                echo '积分不足'.$user['cpzj'].',请先充值！';
                exit;
            }
            //从主号减掉钱
            $fck->execute('update __TABLE__ set agent_cash=agent_cash-'.$user['cpzj'].' where id='.$id);
            //激活这个人
            $fck->execute('update __TABLE__ set fanli_money=fanli_money-'.$fen_day.' where id='.$id);


            //加入history
            $fck->addencAdd($id,$user['user_id'],-$user['cpzj'],6);
            //加入收
            $shouru=M('shouru');
            $data1 = array();
            $data1['uid'] = $id;
            $data1['user_id'] = $user['user_id'];
            $data1['in_money'] = $user['cpzj'];
            $data1['in_time'] = time();
            $data1['in_bz'] = "续费";
            $shouru->add($data1);

            //统计单数
            // $fck->xiangJiao($id,$user['f4']);

            //算出奖金
            // $fck->getusjj($id,1,$user['cpzj'],$user['f4']);

            echo '续费成功';
        }else{
            echo '操作错误';
            exit;
        }



    }
    //自己激活
    public function active_bak(){
        $this->_checkUser();
        //续费需要多少钱
        $fee_rs=M('fee')->find();
        $one_money=$fee_rs['s9'];
        $fen_day=$fee_rs['s11'];

        //检查用户
        $fck=D('Fck');
        $id=$_SESSION[C('USER_AUTH_KEY')];
        $user=$fck->where('id='.$id)->find();
        if($user){
            //扣钱续费
            $user_agent_cash=$user['agent_cash'];
            //需要多少钱
            $need=$user['cpzj'];
            if($user_agent_cash<$need){
                echo '积分不足'.$need.',请先充值！';
                exit;
            }
            $fck->execute('update __TABLE__ set agent_cash=agent_cash-'.$need.' where id='.$id);


            $shouru = M ('shouru');
            $fee = M('fee');
            $Guzhi = A('Guzhi');
            $fee_rs = $fee->field('s2,s3,s9')->find();
            $s9 = $fee_rs['s9'];//投资金额
            $where = array();
            $where['id'] = $id;
            $where['is_pay'] = 0;
            $field = "*";
            $vo = $fck ->where($where)->field($field)->order('id asc')->select();
            $nowdate = strtotime(date('c'));
            $nowday = strtotime(date('Y-m-d'));
            $nowmonth = date('m');
            $fck->emptyTime();

            foreach($vo as $voo){
                //传的会员级别
                $aa = "u_level".$voo['id'];
                $ulevel = $_POST[$aa];
                $f4 = $voo['f4'];

                //给推荐人添加推荐人数或单数
                $fck->query("update __TABLE__ set `re_nums`=re_nums+1,re_f4=re_f4+1 where `id`=".$voo['re_id']);
                $nnrs = $fck->where('is_pay>0')->field('n_pai')->order('n_pai desc')->find();
                $mynpai = ((int)$nnrs['n_pai'])+1;


                $in_gp = $s9[$ulevel-1]/2;//获得的股票金额

                //接点人信息  开通以后就是小公排
                $arry = array();
                $arry = $this->gongpaixtsmall($voo['re_id']);
                $father_id      = $arry['father_id'];
                $father_name = $arry['father_name'];
                $TreePlace     = $arry['treeplace'];
                $p_level        = $arry['p_level'];
                $p_path        = $arry['p_path'];
                $u_pai          = $arry['u_pai'];

                $data = array();
                $data['is_pay'] = 1;
                $data['pdt'] = $nowdate;
                $data['open'] = 1;
                $data['u_level'] = $ulevel;//审核时候的会员级别
                //默认开通是一个单 start
                $data['cpzj'] = $s9;//审核时候的投资金额
                $data['f4'] = 1;
                //默认开通是一个单 end
                $data['get_date'] = $nowday;
                $data['fanli_time'] = $nowday;//当天没有分红奖
                $data['agent_lock'] = $in_gp;//
                $data['agent_gp'] = $in_gp;//
                $data['gp_num'] = $in_gp;//
                $data['n_pai'] = $mynpai;
                $data['is_zy']  = $voo['id'];

                //  开通以后就是小公排
                $data['father_id'] = $father_id;
                $data['father_name'] = $father_name;
                $data['treeplace'] = $TreePlace;
                $data['p_level'] = $p_level;
                $data['p_path'] = $p_path;
                $data['u_pai'] = $u_pai;

                //开通会员
                $result = $fck->where('id='.$voo['id'])->save($data);
                unset($data,$varray);

                $data = array();
                $data['uid'] = $voo['id'];
                $data['user_id'] = $voo['user_id'];
                $data['in_money'] = $s9*$f4;
                $data['in_time'] = time();
                $data['in_bz'] = "新会员加入";
                $shouru->add($data);
                unset($data);


                //统计单数
                // $fck->xiangJiao($voo['id'],$f4);

                //算出奖金
                // $fck->getusjj($voo['id'],1,$s9*$f4,$f4);

                //上面开通的会员单数f4被修改为1单,cpzj修改为5000，这样的话，多出来的就作子帐号
                $this->_OpenFormyself($voo['id'],$f4-1);
                //上面开通的会员单数f4被修改为1单,cpzj修改为5000，这样的话，多出来的就作子帐号
            }
            echo 'success';
            exit;
        }else{
            echo '操作错误';
            exit;
        }



    }
    //自己激活
    public function active(){
        $this->_checkUser();
        //续费需要多少钱
        $fee_rs=M('fee')->find();
        $one_money=$fee_rs['s9'];
        $fen_day=$fee_rs['s11'];

        //检查用户
        $fck=D('Fck');
        $id=$_SESSION[C('USER_AUTH_KEY')];
        $user=$fck->where('id='.$id)->find();
        if($user){
            //扣钱续费
            $user_agent_cash=$user['agent_cash'];
            //需要多少钱
            $need=$user['cpzj'];
            if($user_agent_cash<$need){
                echo '积分不足'.$need.',请先充值！';
                exit;
            }
            $fck->execute('update __TABLE__ set agent_cash=agent_cash-'.$need.' where id='.$id);


            $shouru = M ('shouru');
            $fee = M('fee');
            $Guzhi = A('Guzhi');
            $fee_rs = $fee->field('s2,s3,s9')->find();
            $s9 = $fee_rs['s9'];//投资金额
            $where = array();
            $where['id'] = $id;
            $where['is_pay'] = 0;
            $field = "*";
            $vo = $fck ->where($where)->field($field)->order('id asc')->select();
            $nowdate = strtotime(date('c'));
            $nowday = strtotime(date('Y-m-d'));
            $nowmonth = date('m');
            $fck->emptyTime();

            foreach($vo as $voo){
                //传的会员级别
                $aa = "u_level".$voo['id'];
                $ulevel = $_POST[$aa];
                $f4 = $voo['f4'];

                //给推荐人添加推荐人数或单数
                $fck->query("update __TABLE__ set `re_nums`=re_nums+1,re_f4=re_f4+{$f4} where `id`=".$voo['re_id']);
                $nnrs = $fck->where('is_pay>0')->field('n_pai')->order('n_pai desc')->find();
                $mynpai = ((int)$nnrs['n_pai'])+1;


                $in_gp = $s9[$ulevel-1]/2;//获得的股票金额

                //接点人信息  开通以后就是小公排
                $arry = array();
                $arry = $this->gongpaixtsmall($voo['re_id']);
                $father_id      = $arry['father_id'];
                $father_name = $arry['father_name'];
                $TreePlace     = $arry['treeplace'];
                $p_level        = $arry['p_level'];
                $p_path        = $arry['p_path'];
                $u_pai          = $arry['u_pai'];

                $data = array();
                $data['is_pay'] = 1;
                $data['pdt'] = $nowdate;
                $data['open'] = 1;
                $data['u_level'] = $ulevel;//审核时候的会员级别
                //默认开通是一个单 start
                //默认开通是一个单 end
                $data['get_date'] = $nowday;
                $data['fanli_time'] = $nowday;//当天没有分红奖
                $data['agent_lock'] = $in_gp;//
                $data['agent_gp'] = $in_gp;//
                $data['gp_num'] = $in_gp;//
                $data['n_pai'] = $mynpai;
                $data['is_zy']  = $voo['id'];

                //  开通以后就是小公排
                $data['father_id'] = $father_id;
                $data['father_name'] = $father_name;
                $data['treeplace'] = $TreePlace;
                $data['p_level'] = $p_level;
                $data['p_path'] = $p_path;
                $data['u_pai'] = $u_pai;

                //开通会员
                $result = $fck->where('id='.$voo['id'])->save($data);
                unset($data,$varray);

                $data = array();
                $data['uid'] = $voo['id'];
                $data['user_id'] = $voo['user_id'];
                $data['in_money'] = $voo['cpzj'];
                $data['in_time'] = time();
                $data['in_bz'] = "新会员加入";
                $shouru->add($data);
                unset($data);


                //统计单数
                $fck->xiangJiao($voo['id'],$f4);

                //算出奖金
                // $fck->getusjj($voo['id'],1,$voo['cpzj'],$f4);

                //上面开通的会员单数f4被修改为1单,cpzj修改为5000，这样的话，多出来的就作子帐号
//                $this->_OpenFormyself($voo['id'],$f4-1);
                //上面开通的会员单数f4被修改为1单,cpzj修改为5000，这样的话，多出来的就作子帐号
            }
            echo '激活成功';
            exit;
        }else{
            echo '操作错误';
            exit;
        }



    }



    // 后台首页 查看系统信息
    public function friends() {
        $this->_checkUser();
        $ppfg = $_POST['ppfg'];
        $id = $_SESSION[C('USER_AUTH_KEY')];  //登录AutoId
        $fck = M('fck');
        $cash = M ('cash');
        $history = M ('history');

        //查询
        $fck_rs = $fck -> where('id='.$id)->field('*') -> find();
        $this -> assign('fck_rs',$fck_rs);//总奖金

        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $this->assign ( 'server', $see );
        $this->display();
    }

    public function twodemcode(){
        vendor("phpqrcode.phpqrcode");
        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $id = $_SESSION[C('USER_AUTH_KEY')];
        $fck_rs = M('fck')->where('id='.$id)->field('user_id')->find();
        $data ="http://$see/Reg/us_reg/rid/{$fck_rs['user_id']}";
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 4;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false

        // 生成的文件名
        ob_end_clean();//清空缓冲区
        QRcode::png($data, $false, $level, $size);
    }

    //这个是获取微信的api
    public function erweima(){


        $fck2 = M('fck2');
        $find = $fck2->where('fck_id='.$_SESSION[C('USER_AUTH_KEY')])->find();
        if (!$find){
            echo '<font style="color: red; font-size: 39px; text-align: center;display:inline-block;padding: 600px 0 0 0; ">你还没购买VIP购物卡!请先购买后即可生成推广二维码</font>';
            exit();
        }


//        $fee_rs = M('fee')->field('s8')->find();
//        $s8 = explode('|',$fee_rs['s8']);
//        $appid  = $s8[0];
//        $secret = $s8[1];

        $appid_info  = C('WEIXINPAY_CONFIG');
        $appid = $appid_info['APPID'];
        $secret = $appid_info['APPSECRET'];

        $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false );
        $result = curl_exec($ch);
        curl_close($ch);
        $result1 = json_decode($result,true);


        $dd=$result1['access_token'];

        $id=$_SESSION[C('USER_AUTH_KEY')];

        $url1="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$dd."";

        $post_data='{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$id.'}}}';

        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_HEADER, 0);
        curl_setopt($ch1, CURLOPT_URL, $url1);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ($ch1, CURLOPT_SSL_VERIFYPEER, false );
        $result1 = curl_exec($ch1);
        curl_close($ch1);


        $result2=json_decode($result1,true);
        $ticket = $result2['ticket'];
        $ticket1 = urlencode($ticket);
        $qrurl="http://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket1."";
//        $dingdanhao=date('Ymd').rand(1000000000,9999999999).'p';
        $dingdanhao=$_SESSION[C('USER_AUTH_KEY')].'p';   //以会员id为下标
        ob_start();
        readfile($qrurl);
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);






        $qrfile = $_SERVER['CONTEXT_DOCUMENT_ROOT'] . '\Public\Images\weixin_code\base\qrfile.jpg';
        $fp2=@fopen($qrfile, "w");
        fwrite($fp2,$img,$size);
        fclose($fp2);

        $bgfile = $_SERVER['CONTEXT_DOCUMENT_ROOT'] .  '/Public/Images/weixin_code/base/222.png';
        ob_end_clean();
        if(file_exists($bgfile)){

            header("Content-type: image/jpeg");

            $percent = 0.4;  //图片压缩比
            list($width, $height) = getimagesize($qrfile); //获取原图尺寸
            //缩放尺寸
            $newwidth = $width * $percent;
            $newheight = $height * $percent;
            $src_im = imagecreatefromjpeg($qrfile);
            $dst_im = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
            $weixin_erweima = $_SERVER['CONTEXT_DOCUMENT_ROOT'] .  "/Public/Images/weixin_code/weixin_erweima.png";
            imagejpeg($dst_im,$weixin_erweima); //输出压缩后的图片
            imagedestroy($dst_im);
            imagedestroy($src_im);

            $qrfile = $_SERVER['CONTEXT_DOCUMENT_ROOT'] .  "/Public/Images/weixin_code/weixin_erweima.png";

            $bg = imagecreatefrompng($bgfile);   //本函数用来取出一张 PNG 格式图形，通当取出当背景或者基本的画布样本使用
//            $qr = imagecreatefromjpeg($qrfile);   //原来的
            $qr = imagecreatefromjpeg($qrfile);   //修改后的
            imagealphablending($bg, false);      //允许在真彩色图像上使用两种不同的绘画模式
            imagesavealpha($bg, true);           //设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息（与单一透明色相反）。意思是不要丢了$thumb图像的透明色;
            // Copy and merge
//            imagecopymerge($bg, $qr, 120, 120, 0, 0, 430, 430, 100);
            imagecopymerge($bg, $qr, 180,400, 0, 0, 172,172, 70);  //合并图像 imagecopymerge 函数（水印制作实例）
            //header('Content-Type: image/png');
            $newimg = $_SERVER['CONTEXT_DOCUMENT_ROOT'] .  "/Public/Images/weixin_code/".$dingdanhao.".png";
            imagepng($bg, $newimg);
            imagedestroy($qr);
            imagedestroy($bg);


            $fck=M('fck');
            $id=$_SESSION[C('USER_AUTH_KEY')];
            $fck_rs=$fck->where('id='.$id)->field('us_img,nickname,user_id')->find();
            //$im=$fck_rs['us_img'];
            $name=$fck_rs['user_id'];
            /* ob_start();
             readfile($im);
             $img1 = ob_get_contents();
             ob_end_clean();
             $size1 = strlen($img1);

             $qrfile1 = $_SERVER['CONTEXT_DOCUMENT_ROOT'] . '\Public\Images\aaaa.jpg';

             $fp21=@fopen($qrfile1, "w");
             fwrite($fp21,$img1,$size1);
             fclose($fp21);
            // $lst=$this->thumb($qrfile1,)
              $t=$newimg;
              ob_end_clean();
              $bg2 = imagecreatefrompng($t);
              $qr2 = imagecreatefromjpeg($qrfile1);
              imagealphablending($bg2, false);
              imagesavealpha($bg2, true);
              // Copy and merge
              imagecopymerge($bg2, $qr2, 50, 1000, 0, 0, 430, 430, 100);
              $newimg1 = $_SERVER['CONTEXT_DOCUMENT_ROOT'] .  "/Public/Images/".$dingdanhao."-".$id.".png";
              imagepng($bg2, $newimg1);
              imagedestroy($qr2);
              imagedestroy($bg2);*/
            $dst = imagecreatefromstring(file_get_contents($newimg));

//            echo $dst;
            $font = './simsun.ttc';//字体
//            $black = imagecolorallocate($dst, 0x00, 0x00, 0x00);//字体颜色
            $black = imagecolorallocate($dst, 233, 14, 91);//字体颜色
//            echo $black;
//            exit();
            imagefttext($dst, 18, 0, 170, 85, $black, $font, $name);
            //imagefttext($image, $size, $angle, $x, $y, $color, $fontfile, $text);
            //$image 这个是画布资源，无需再解释；
            //$size字体大小，其长度单位依赖于GD库的版本，对于GD1来说是像素，对于GD2来说是磅
            //$angle是旋转角度
            //$x，$y 被绘制字符串的第一个字符的基线点。单位是像素。这里涉及到字体设计的基本知识--基线。这个点绝对不是左上角，而具体是什么取决于所使用的字体是如何设计的。对于宋体、楷体、黑体等常见的字体中的汉字，这个点大概位于字体的左下部分；而对于英文字母和标点符号，则各不相同
            //$color 字体的颜色
            //$fontfile 字体文件
            //$text 要渲染的字符串   “如  水印文字  ”
            $newimg2 = $_SERVER['CONTEXT_DOCUMENT_ROOT'] .  "/Public/Images/weixin_code/".$dingdanhao."_".$id."_1.png";
            header('Content-Type: png');
            imagepng($dst,$newimg2);
            imagedestroy($dst);

            //echo "<img src='{$newimg}'>";
            //exit;
            //echo 'file is exists.';
        }else{
            echo 'png not exists!';
        }
        $this->assign ( 'user_id',$fck_rs['user_id']);
        $this->assign ( 'url2',"/Public/Images/weixin_code/".$dingdanhao."_".$id."_1.png");

//        unlink($newimg2);


        /*
        import('@.ORG.Image');
         $Image = new Image();

       $Image->water('/__PUBLIC__/Images/png.png','/'.$url2.'');
    */




        $this->display();

    }
    //普通二维码推广
    public function create_code(){
        $fck2 = M('fck2');
        $find = $fck2->where('fck_id='.$_SESSION[C('USER_AUTH_KEY')])->find();
        if (!$find){
            echo '<font style="color: red; font-size: 39px; text-align: center;display:inline-block;padding: 600px 0 0 0; ">你还没购买VIP购物卡!请先购买后即可生成推广二维码</font>';
            exit();
        }
        $this->display();

    }

    public function hello(){

        if ( $_GET['type'] !=1){
            $_SESSION = array();
        }
        $link_rs = M('link')->find();
        $s12 = M('fee')->getField('s12');

        $this->assign('s12',$s12);
        $this->assign('link_rs',$link_rs);
        $this->display();
    }

        public function extension(){
        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $id = $_SESSION[C('USER_AUTH_KEY')];
        $fck_rs = M('fck')->where('id='.$id)->field('user_id')->find();
        $data ="http://$see/Reg/us_reg/rid/".$fck_rs['user_id'];
        $this->assign('reg_link',$data);
        $this->assign('user_id',$fck_rs['user_id']);
        $this->display();
    }
    public function ExtensionCode(){
        vendor("phpqrcode.phpqrcode");
        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $id = $_SESSION[C('USER_AUTH_KEY')];
        $fck_rs = M('fck')->where('id='.$id)->field('user_id')->find();
        $data ="http://$see/Reg/us_reg/rid/".$fck_rs['user_id'];
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 34;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        $c = ($_SERVER['DOCUMENT_ROOT'] . (__ROOT__) . "/Public/Images/weixin_code/");
        $path = "$c";
        // 生成的文件名
//        $fileName = $path.$id.'.png';
        // 生成的文件名
        ob_end_clean();//清空缓冲区
        QRcode::png($data, $fileName, $level, $size);
    }


    //普通二维码推广
    public function create_code_img(){

        vendor("phpqrcode.phpqrcode");
        $see = $_SERVER['HTTP_HOST'].__APP__;
        $see = str_replace("//","/",$see);
        $id = $_SESSION[C('USER_AUTH_KEY')];
        $fck_rs = M('fck')->where('id='.$id)->field('user_id')->find();
        $data ="http://$see/Reg/us_reg/rid/{$fck_rs['user_id']}";
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 5;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
        // $c = ($_SERVER['DOCUMENT_ROOT'] . (__ROOT__) . "/Public/Images/weixin_code/");
        // $path = "$c";
        // 生成的文件名
        // $fileName = $path.$id.'.png';

        // 生成的文件名
        ob_end_clean();//清空缓冲区
        QRcode::png($data, $fileName, $level, $size);

//         $bgfile = $_SERVER['DOCUMENT_ROOT'] . (__ROOT__) . "/Public/Images/weixin_code/base/222.png";

//             header("Content-type: image/png");


//             $qrfile = $fileName;


//             $percent = 1.5;  //图片压缩比
//             list($width, $height) = getimagesize($qrfile); //获取原图尺寸
//             //缩放尺寸
//             $newwidth = $width * $percent;
//             $newheight = $height * $percent;
//             $src_im = imagecreatefrompng($qrfile);
//             $dst_im = imagecreatetruecolor($newwidth, $newheight);
//             imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
//             $weixin_erweima = $_SERVER['DOCUMENT_ROOT'] . (__ROOT__) . "/Public/Images/weixin_code/".$id."_1.png";
//             imagepng($dst_im,$weixin_erweima); //输出压缩后的图片
//             imagedestroy($dst_im);
//             imagedestroy($src_im);



//             $bg = imagecreatefrompng($bgfile);   //本函数用来取出一张 PNG 格式图形，通当取出当背景或者基本的画布样本使用
//             $qr = imagecreatefrompng($weixin_erweima);   //修改后的
//             imagealphablending($bg, false);      //允许在真彩色图像上使用两种不同的绘画模式
//             imagesavealpha($bg, true);           //设置标记以在保存 PNG 图像时保存完整的 alpha 通道信息（与单一透明色相反）。意思是不要丢了$thumb图像的透明色;

//             imagecopymerge($bg, $qr, 200,400, 0, 0, 300,300, 70);  //合并图像 imagecopymerge 函数（水印制作实例）
//             //header('Content-Type: image/png');
//             $newimg = $_SERVER['DOCUMENT_ROOT'] . (__ROOT__) . "/Public/Images/weixin_code/".$id."_2.png";
//             imagepng($bg, $newimg);
//             imagedestroy($qr);
//             imagedestroy($bg);


//             $fck=M('fck');
//             $id=$_SESSION[C('USER_AUTH_KEY')];
//             $fck_rs=$fck->where('id='.$id)->field('us_img,nickname,user_id')->find();

// //            $name=$fck_rs['user_id'];
//             $name='';



//         header("Content-type: image/png");

// //        字体水印部分

//             $dst = imagecreatefromstring(file_get_contents($newimg));

//             $font = './simsun.ttc';//字体
// //            $font = "C:\WINDOWS\Fonts\SIMHEI.TTF";//字体  本地字体不见了


//             $black = imagecolorallocate($dst, 233, 14, 91);//字体颜色

//             imagefttext($dst, 18, 0, 170, 85, $black, $font, $name);
//             //imagefttext($image, $size, $angle, $x, $y, $color, $fontfile, $text);
//             //$image 这个是画布资源，无需再解释；
//             //$size字体大小，其长度单位依赖于GD库的版本，对于GD1来说是像素，对于GD2来说是磅
//             //$angle是旋转角度
//             //$x，$y 被绘制字符串的第一个字符的基线点。单位是像素。这里涉及到字体设计的基本知识--基线。这个点绝对不是左上角，而具体是什么取决于所使用的字体是如何设计的。对于宋体、楷体、黑体等常见的字体中的汉字，这个点大概位于字体的左下部分；而对于英文字母和标点符号，则各不相同
//             //$color 字体的颜色
//             //$fontfile 字体文件
//             //$text 要渲染的字符串   “如  水印文字  ”
//             $newimg2 = $_SERVER['DOCUMENT_ROOT'] . (__ROOT__) . "/Public/Images/weixin_code/".$id."_3.png";
//             header('Content-Type: png');
// //            imagepng($dst);
//             imagepng($dst,$newimg2);
//             imagedestroy($dst);


//             unlink($qrfile);
//             unlink($weixin_erweima);
//             unlink($newimg);
//         $this->assign ( 'url2',(__ROOT__) ."/Public/Images/weixin_code/".$id."_3.png");
//         $this->assign ( 'reg_link',$data);

//         $this->display('create_code2');

    }
    public function yanzheng() {




        $code=$_GET['code'];


        $appid_info  = C('WEIXINPAY_CONFIG');
        $appid = $appid_info['APPID'];
        $secret = $appid_info['APPSECRET'];

        $url="https://api.weixin.qq.com/sns/oauth2/access_token?";
        $post_data="appid='".$appid."'&secret='".$secret."'&code=".$code."&grant_type=authorization_code";


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false );

        $result = curl_exec($ch);
        if(curl_errno($ch)){
            // 显示报错信息；终止继续执行
            die(curl_error($ch));
        }
        curl_close($ch);
        $result2 = json_decode($result,true);

        $dd=$result2['access_token'];

        $pid=$result2['openid'];
        $_SESSION['login_count']        =   $pid;
        $_SESSION['login_isAgent']      =   $dd;



        $url1="https://api.weixin.qq.com/sns/userinfo?";
        $post_data1="access_token=".$dd."&openid=".$pid."&lang=zh_CN";
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_HEADER, 0);
        curl_setopt($ch1, CURLOPT_URL, $url1);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $post_data1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ($ch1, CURLOPT_SSL_VERIFYPEER, false );

        $result1 = curl_exec($ch1);
        $data = json_decode($result1,true);

        $fck=M('fck');
        $time=time();


        $a=$fck->where("appid='".$pid."'")->find();
        if(!$a){

            // $aid=$_SESSION['loginUseracc'];


            $tt=array();
            $tt['appid']=$pid;
            $tt['nickname']=$data['nickname'];
            $tt['get_ceng']=$data['sex'];
            $tt['us_img']=$data['headimgurl'];
            $tt['u_level']=0;
            $tt['pdt']    =$time;
            $tt['new_login_time']=$time;
            $rs=$fck->add($tt);
            if($rs){
                $aa=$fck->where("user_id='".$pid."'")->find();
                $_SESSION[C('USER_AUTH_KEY')]    =   $aa['id'];
            }

        }

        else{
            $fck->execute("update __TABLE__ set nickname='".$data['nickname']."',us_img='".$data['headimgurl']."',get_ceng=".$data['sex'].",new_login_time=".$time." where user_id='".$pid."'");

            $_SESSION[C('USER_AUTH_KEY')]    =   $a['id'];


        }
        $gouwu=A('Gouwu');
        $gouwu->Buycp();
//        U('Gouwu/Buycp');

    }

    public function yanzheng1() {




        $code=$_GET['code'];


        $url="https://api.weixin.qq.com/sns/oauth2/access_token?";
        $post_data="appid=wxdfc6fec1902c9870&secret=2f6643d8d42a16646da60953e61f2af2&code=".$code."&grant_type=authorization_code";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false );

        $result = curl_exec($ch);
        if(curl_errno($ch)){
            // 显示报错信息；终止继续执行
            die(curl_error($ch));
        }
        curl_close($ch);
        $result2 = json_decode($result,true);

        $dd=$result2['access_token'];
        $pid=$result2['openid'];
        $_SESSION['login_count']        =   $pid;
        $_SESSION['login_isAgent']      =   $dd;






        $url1="https://api.weixin.qq.com/sns/userinfo?";
        $post_data1="access_token=".$dd."&openid=".$pid."&lang=zh_CN";
        $ch1 = curl_init();
        curl_setopt($ch1, CURLOPT_POST, 1);
        curl_setopt($ch1, CURLOPT_HEADER, 0);
        curl_setopt($ch1, CURLOPT_URL, $url1);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, $post_data1);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch1, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt ($ch1, CURLOPT_SSL_VERIFYPEER, false );

        $result1 = curl_exec($ch1);
        $data = json_decode($result1,true);

        $fck=M('fck');
        $time=time();


        $a=$fck->where("user_id='".$pid."'")->find();
        if(!$a){

            // $aid=$_SESSION['loginUseracc'];


            $tt=array();
            $tt['user_id']=$pid;
            $tt['nickname']=$data['nickname'];
            $tt['get_ceng']=$data['sex'];
            $tt['us_img']=$data['headimgurl'];
            $tt['u_level']=0;
            $tt['pdt']    =$time;
            $tt['new_login_time']=$time;
            $rs=$fck->add($tt);
            if($rs){
                $aa=$fck->where("user_id='".$pid."'")->find();
                $_SESSION[C('USER_AUTH_KEY')]    =   $aa['id'];
            }
        }

        else{
            $fck->execute("update __TABLE__ set nickname='".$data['nickname']."',us_img='".$data['headimgurl']."',get_ceng=".$data['sex'].",new_login_time=".$time." where user_id='".$pid."'");

            $_SESSION[C('USER_AUTH_KEY')]    =   $a['id'];


        }

        $this->display('Gouwu/Buycp');

    }

    // 用户登录页面
    public function login() {
        $fee = M('fee');
        $fee_rs = $fee->field('str21')->find();
        $this->assign('fflv',$fee_rs['str21']);
        unset($fee,$fee_rs);

        $this->display();
    }

    // 用户登录页面
//    public function login() {
//        $fee = M('fee');
//        $fee_rs = $fee->field('str21')->find();
//        $this->assign('fflv',$fee_rs['str21']);
//        unset($fee,$fee_rs);
////        $this->yanzheng();
////        $this->display();
//    }
    public function checklogin2() {
        //处理GET数据
        $appid=C('WEIXINPAY_CONFIG')['APPID'];//填写AppID　　
        $secret=C('WEIXINPAY_CONFIG')['APPSECRET'];//填写Secret
        // 第一：获取code
        $code=$_GET['code'];

        // 第二：获取access_token
        $a=$this->curl($appid,$secret,$code);
        $access_token=$a['access_token'];
        $openid=$a['openid'];
        import ( '@.ORG.RBAC' );
        $map=array('appid'=>$openid);
        $fck = M('fck');
        $field = 'id,user_id,password,is_pay,is_lock,nickname,user_name,is_agent,user_type,last_login_time,login_count,is_boss,passopen,father_id';
        $authInfo = $fck->where($map)->field($field)->find();
        if($authInfo){
            if($authInfo['father_id']==0&&$authInfo['id']!=1){
//                $this->error('还未购买公排，无法登陆');
            }
            $_SESSION['user_pwd2']          =   $authInfo['passopen'];
            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
            $_SESSION['loginUseracc']		=	$authInfo['user_id'];//用户名
            $_SESSION['loginNickName']		=	$authInfo['nickname'];//会员名
            $_SESSION['loginUserName']		=	$authInfo['user_name'];//开户名
            $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
            //$_SESSION['login_count']	    =	$authInfo['login_count'];
            $_SESSION['login_isAgent']	    =	$authInfo['is_agent'];//是否报单中心
            $_SESSION['modal_agreement']=			$authInfo['id'];//用户协议的判断
            $_SESSION['UserMktimes']        = 	mktime();
            //身份确认 = 用户名+识别字符+密码
            $_SESSION['login_sf_list_u']    = md5($authInfo['user_id'].'wodetp_new_1012!@#'.$authInfo['password'].$_SERVER['HTTP_USER_AGENT']);

            //登录状态
            $user_type = md5($_SERVER['HTTP_USER_AGENT'].'wtp'.rand(0,999999));
            $_SESSION['login_user_type'] = $user_type;
            $where['id'] = $authInfo['id'];
            $fck->where($where)->setField('user_type',$user_type);
//			$fck->where($where)->setField('last_login_time',mktime());
            //管理员

            $parmd = $this->_cheakPrem();
            if($authInfo['id'] == 1||$parmd[11]==1) {
                $_SESSION['administrator']		=	1;
            }else{
                $_SESSION['administrator']		=	2;
            }

            $fck->execute("update __TABLE__ set last_login_time=new_login_time,last_login_ip=new_login_ip,new_login_time=".time().",new_login_ip='".$_SERVER['REMOTE_ADDR']."' where id=".$authInfo['id']);
            // 缓存访问权限
            RBAC::saveAccessList();
            $this->redirect('Index/index', array(), 1, '页面跳转中...');
            $this->success('登录成功！');
        }else{
            $this->error('找不到会员信息，无法登陆');
//            $this->error('找不到会员信息，无法登陆'.$openid);
        }

    }
    function curl($appid,$secret,$code)
    {
        $ch = curl_init();
        //curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret);
        curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno'.curl_error($ch);
        }
        curl_close($ch);
        $arr= json_decode($tmpInfo,true);
        return $arr;
    }
    public function PayResult() {
        $fee=M('fee');
        $fee_rs=$fee->find();
        $s15=$fee_rs['s15'];

        //MD5私钥
        $MD5key = $s15;
        //订单号
        $BillNo = $_POST["BillNo"];
        //金额
        $Amount = $_POST["Amount"];
        //支付状态
        $Succeed = $_POST["Succeed"];
        //支付结果
        $Result = $_POST["Result"];
        //取得的MD5校验信息
        $SignMD5info = $_POST["SignMD5info"];
        //备注
        $Remark = $_POST["Remark"];


        //校验源字符串
        $md5src = $BillNo."&".$Amount."&".$Succeed."&".$MD5key;
        //MD5检验结果
        $md5sign = strtoupper(md5($md5src));

        if ($SignMD5info==$md5sign){
            if($Succeed=="88"){
                $chongzhi=M('chongzhi');
                $bill=$chongzhi->where("zhuanghao='{$BillNo}' and is_pay=0")->find();
                if($bill){
                    $id=$bill['uid'];
                    $fck=D('Fck');
                    $user=$fck->where('id='.$id)->find();
                    if($user){
                        $fck->execute('update __TABLE__ set agent_cash=agent_cash+'.$Amount.' where id='.$id);
                        $data['is_pay']=1;
                        $chongzhi->where("zhuanghao='{$BillNo}'")->save($data);
                        $this->success('支付成功！');
                    }
                }
            }else{
                $this->error('错误！'.$Result);
            }
        }else{
            $this->error('错误！');
        }


    }

    public function index()
    {
        //如果通过认证跳转到首页
        redirect(__APP__);
    }

    // 用户登出
    public function LogOut(){
        $_SESSION = array();
        //unset($_SESSION);
//        $this->assign('jumpUrl',__URL__.'/login/');
        $this->assign('jumpUrl',__APP__);
        $this->success('退出成功！');
    }

    // 登录检测
    public function checkLogin() {
        if(empty($_POST['account'])) {
            $this->error('请输入帐号！');
        }elseif (empty($_POST['password'])){
            $this->error('请输入密码！');
        }elseif (empty($_POST['verify'])){
            $this->error('请输入验证码！');
        }
        $fee = M ('fee');
//		$sel = (int) $_POST['radio'];
//		if($sel <=0 or $sel >=3){
//			$this->error('非法操作！');
//			exit;
//		}
//		if($sel != 1){
//			$this->error('暂时不支持英文版登录！');
//			exit;
//		}

        //生成认证条件
        $map            =   array();
        // 支持使用绑定帐号登录
        $map['user_id']	   = $_POST['account'];
//		$map['nickname'] = $_POST['account'];   //用户名也可以登录
//		$map['_logic']    = 'or';
        //$map['_complex']    = $where;
        //$map["status"]	=	array('gt',0);
        if($_SESSION['verify'] != md5($_POST['verify'])) {
            $this->error('验证码错误！');
        }
        import ( '@.ORG.RBAC' );
        $fck = M('fck');
        $field = 'id,user_id,password,is_pay,is_lock,nickname,user_name,is_agent,user_type,last_login_time,login_count,is_boss';
        $authInfo = $fck->where($map)->field($field)->find();

        //使用用户名、密码和状态的方式进行认证
        if(false == $authInfo) {
            $this->error('帐号或密码错误！');
        }else {
            if($authInfo['password'] != md5($_POST['password'])) {
                $this->error('帐号或密码错误！');
                exit;
            }

            if($_POST['lang'] == 1){
                $this->error('英文版本暂时无法登陆，请选择中文版本！');
                exit;
            }

            if($_POST['agent']==2 && $authInfo['is_agent']<$_POST['agent']){
                $this->error('您为非报单中心,请选择会员登录入口！');
                exit;
            }

    //         if ($authInfo['is_pay'] <1){
				// $this->error('用户尚未开通，暂时不能登录系统！');
				// exit;
    //         }
            if ($authInfo['is_lock']!=0){
                $this->error('用户已锁定，请与管理员联系！');
                exit;
            }
            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
            $_SESSION['loginUseracc']		=	$authInfo['user_id'];//用户名
            $_SESSION['loginNickName']		=	$authInfo['nickname'];//会员名
            $_SESSION['loginUserName']		=	$authInfo['user_name'];//开户名
            $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
            //$_SESSION['login_count']	    =	$authInfo['login_count'];
            $_SESSION['login_isAgent']	    =	$authInfo['is_agent'];//是否报单中心
            $_SESSION['modal_agreement']=			$authInfo['id'];//用户协议的判断
            $_SESSION['UserMktimes']        = 	mktime();
            //身份确认 = 用户名+识别字符+密码
            $_SESSION['login_sf_list_u']    = md5($authInfo['user_id'].'wodetp_new_1012!@#'.$authInfo['password'].$_SERVER['HTTP_USER_AGENT']);

            //登录状态
            $user_type = md5($_SERVER['HTTP_USER_AGENT'].'wtp'.rand(0,999999));
            $_SESSION['login_user_type'] = $user_type;
            $where['id'] = $authInfo['id'];
            $fck->where($where)->setField('user_type',$user_type);
//			$fck->where($where)->setField('last_login_time',mktime());
            //管理员

            $parmd = $this->_cheakPrem();
            if($authInfo['id'] == 1||$parmd[11]==1) {
                $_SESSION['administrator']		=	1;
            }else{
                $_SESSION['administrator']		=	2;
            }

//			//管理员
//			if($authInfo['is_boss'] == 1) {
//            	$_SESSION['administrator'] =	1;
//            }elseif($authInfo['is_boss'] == 2){
//            	$_SESSION['administrator'] = 3;
//            }elseif($authInfo['is_boss'] == 3){
//                $_SESSION['administrator']  = 4;
//            }elseif($authInfo['is_boss'] == 4){
//                $_SESSION['administrator'] = 5;
//            }elseif($authInfo['is_boss'] == 5){
//                $_SESSION['administrator'] =   6;
//            }elseif($authInfo['is_boss'] == 6){
//                $_SESSION['administrator'] =   7;
//            }else{
//				$_SESSION['administrator'] = 2;
//			}

            $fck->execute("update __TABLE__ set last_login_time=new_login_time,last_login_ip=new_login_ip,new_login_time=".time().",new_login_ip='".$_SERVER['REMOTE_ADDR']."' where id=".$authInfo['id']);

            // 缓存访问权限
            RBAC::saveAccessList();
            $this->success('登录成功！');
            sleep(2);
        }
    }
    //二级密码验证
    public function cody(){
        $UrlID = (int)$_GET['c_id'];
        if (empty($UrlID)){
            $this->error('二级密码错误!');
            exit;
        }
        if(!empty($_SESSION['user_pwd2'])){
            $url = __URL__."/codys/Urlsz/$UrlID";
            $this->_boxx($url);
            exit;
        }
        $fck   =  M ('cody');
        $list	=  $fck->where("c_id=$UrlID")->getField('c_id');
        if (!empty($list)){
            $this->assign('vo',$list);
            $this->display('cody');
            exit;
        }else{
            $this->error('二级密码错误!');
            exit;
        }
    }
    //二级验证后调转页面
    public function codys(){
        $Urlsz = $_POST['Urlsz'];
        if(empty($_SESSION['user_pwd2'])){
            $pass  = $_POST['oldpassword'];
            $fck   =  M ('fck');
            if (!$fck->autoCheckToken($_POST)){
                $this->error('页面过期请刷新页面!');
                exit();
            }
            if (empty($pass)){
                $this->error('二级密码错误!');
                exit();
            }

            $where =array();
            $where['id'] = $_SESSION[C('USER_AUTH_KEY')];
            $where['passopen'] = md5($pass);
            $list = $fck->where($where)->field('id')->find();
            if($list == false){
                $this->error('二级密码错误!');
                exit();
            }
            $_SESSION['user_pwd2'] = 1;
        }else{
            $Urlsz = $_GET['Urlsz'];
        }
        switch ($Urlsz){
            case 1:
                $_SESSION['DLTZURL02'] = 'updateUserInfo';
                $bUrl = __URL__.'/updateUserInfo';//修改资料
                $this->_boxx($bUrl);
                break;
            case 2:
                $_SESSION['DLTZURL01'] = 'password';
                $bUrl = __URL__.'/password';//修改密码
                $this->_boxx($bUrl);
                break;
            case 3:
                $_SESSION['DLTZURL01'] = 'pprofile';
                $bUrl = __URL__.'/pprofile';//修改密码
                $this->_boxx($bUrl);
                break;
            case 4:
                $_SESSION['DLTZURL01'] = 'OURNEWS';
                $bUrl = __URL__.'/News';//修改密码
                $this->_boxx($bUrl);
                break;
            default;
                $this->error('二级密码错误!');
                break;
        }
    }

    public function verify()
    {
        ob_clean();
        $type	 =	 isset($_GET['type'])?$_GET['type']:'gif';
        import("@.ORG.Image");
        Image::buildImageVerify();
    }
    //三轨小公排
    public function gongpaixtsmall($uid){
        $fck = M ('fck');
        $mouid=$uid;
        $field = 'id,user_id,p_level,p_path,u_pai';
        $where = 'is_pay>0 and (p_path like "%,'.$mouid.',%" or id='.$mouid.')';

        $re_rs = $fck ->where($where)->order('p_level asc,u_pai+0 asc')->field($field)->select();
        $fck_where = array();
        foreach($re_rs as $vo){
            $faid=$vo['id'];
            $fck_where['is_pay']   = array('egt',0);
            $fck_where['father_id']   = $faid;
            $count = $fck->where($fck_where)->count();
            $sumtp = $fck->where($fck_where)->sum('treeplace');
            //print_r($count);
            //print_r($sumtp);
            if($count==0 && $sumtp==0){
                $father_id=$vo['id'];
                $father_name=$vo['user_id'];
                $TreePlace=0;
                $p_level=$vo['p_level']+1;
                $p_path=$vo['p_path'].$vo['id'].',';
                $u_pai=$vo['u_pai']*2+$TreePlace;

                $arry=array();
                $arry['father_id']=$father_id;
                $arry['father_name']=$father_name;
                $arry['treeplace']=$TreePlace;
                $arry['p_level']=$p_level;
                $arry['p_path']=$p_path;
                $arry['u_pai']=$u_pai;
                return $arry;
                break;
            }elseif($count==1){
                if($sumtp==0){
                    $father_id=$vo['id'];
                    $father_name=$vo['user_id'];
                    $TreePlace=1;
                    $p_level=$vo['p_level']+1;
                    $p_path=$vo['p_path'].$vo['id'].',';
                    $u_pai=$vo['u_pai']*2+$TreePlace;

                    $arry=array();
                    $arry['father_id']=$father_id;
                    $arry['father_name']=$father_name;
                    $arry['treeplace']=$TreePlace;
                    $arry['p_level']=$p_level;
                    $arry['p_path']=$p_path;
                    $arry['u_pai']=$u_pai;
                    return $arry;
                    break;
                }
                if($sumtp==1){
                    $father_id=$vo['id'];
                    $father_name=$vo['user_id'];
                    $TreePlace=0;
                    $p_level=$vo['p_level']+1;
                    $p_path=$vo['p_path'].$vo['id'].',';
                    $u_pai=$vo['u_pai']*2+$TreePlace;

                    $arry=array();
                    $arry['father_id']=$father_id;
                    $arry['father_name']=$father_name;
                    $arry['treeplace']=$TreePlace;
                    $arry['p_level']=$p_level;
                    $arry['p_path']=$p_path;
                    $arry['u_pai']=$u_pai;
                    return $arry;
                    break;
                }
            }
        }
        unset($fck_where,$sumtp,$count);
    }
//	开通子帐号
    public function _OpenFormyself($id,$dan){
        if($dan<1) return;
        $fck = D ('Fck');

        $myrs=$fck->where('id='.$id)->find();
        $uLevel =$dan;

        $fee = M('fee');
        $fee_rs = $fee->field('s12,s9,i5')->find();

        $s12 = $fee_rs['s12'];//互助奖
        $s9 =$fee_rs['s9'];
        $nowdate = strtotime(date('c'));
        $nowday=strtotime(date('Y-m-d'));
        //会员级别
        $count=$dan;
        for($i=0;$i<$count;$i++) {
            $data = array();
            //推荐人 start
            $re_info=$this->last_x_num($id);
            $data['re_path'] = $re_info['re_path'].$re_info['id'].',';  //推薦路徑
            $data['re_id'] = $re_info['id'];                              //推薦人ID
            $data['re_name'] = $re_info['user_id'];                       //推薦人帳號
            $data['re_level'] = $re_info['re_level'] + 1;                 //代數(絕對層數)
            $data['get_ceng'] = $re_info['get_ceng'] + 1;                 //代數(絕對層數)
            //推荐人start
            $fck->execute('update __TABLE__ set re_nums=re_nums+1,re_f4=re_f4+1 where id='.$re_info['id']);
            //推荐人 end

            $data['user_id'] = $myrs['user_id'].(string)($re_info['get_ceng'] + 1);
            $data['bind_account'] = '3333';
            $data['last_login_ip'] = '';                            //最後登錄IP
            $data['verify'] = '0';
            $data['status'] = 1;                             //狀態(?)
            $data['type_id'] = '0';
            $data['last_login_time'] = time();                        //最後登錄時間
            $data['login_count'] = 0;                             //登錄次數
            $data['info'] = '信息';
            $data['name'] = '名稱';
            $data['password'] = $myrs['password'];
            $data['passopen'] = $myrs['passopen'];
            $data['pwd1'] = $myrs['pwd1'];
            $data['pwd2'] = $myrs['pwd2'];

            $data['wenti'] = $myrs['wenti'];
            $data['wenti_dan'] = $myrs['wenti_dan'];

            $data['bank_name'] = $myrs['bank_name'];
            $data['bank_card'] = $myrs['bank_card'];
            $data['user_name'] = $myrs['user_name'];
            $data['nickname'] = $myrs['nickname'];
            $data['bank_province'] = $myrs['bank_province'];
            $data['bank_city'] = $myrs['bank_city'];
            $data['bank_address'] = $myrs['bank_address'];
            //$data['user_post']           = $myrs['user_post'];		   //
            $data['user_code'] = $myrs['user_code'];
            $data['user_address'] = $myrs['user_address'];
            $data['email'] = $myrs['email'];
            $data['qq'] = $myrs['qq'];
            $data['user_tel'] = $myrs['user_tel'];
            $data['rdt'] = time();
            $data['u_level'] = $uLevel + 1;
            $data['y_level'] = $myrs['y_level'];
            $data['cpzj'] = $s9;
            $data['f4'] = 1;
            $data['wlf'] = 0;

            $data['is_pay'] = 1;
            $data['rdt'] = time();
            $data['pdt'] = time();
            $data['open'] = 0;
            $data['get_date'] = $nowday;
            $data['fanli_time'] = $nowday;

            $data['x_num'] = $myrs['id'];

            //  开通以后就是小公排
            $data['father_id'] = 1;
            $data['father_name'] = 1;
            $data['treeplace'] = 1;
            $data['p_level'] = 1;
            $data['p_path'] =1;
            $data['u_pai'] = 1;

            $resss = $fck->add($data);
            echo $fck->getDbError();
            unset($data);
        }
        unset($fck,$where);
    }
    //找出最后一个子账号
    public function last_x_num($id){
        $fck=M('fck');
        $count=$fck->where('x_num='.$id)->count();
        if($count){
            return $fck->where('x_num='.$id)->field('id,user_id,re_path,re_name,re_id,re_level,get_ceng')->order('get_ceng desc')->find();
        }else{
            return $fck->where('id='.$id)->field('id,user_id,re_path,re_name,re_id,re_level,get_ceng')->find();
        }
    }

    //复投   ---- 这部分fck模型中为自动复投
    public function repeat_pay(){
        $id = $_SESSION[C('USER_AUTH_KEY')];
        if ($id){
            $fee_rs = M('fee')->field('str3,str4')->find();
            $fck = D('Fck');

            $info = $fck->where('id='.$id)->field('agent_cf,out_number,can_replay')->find();


            if ( $info['out_number'] <= 0){
                $this->error('你还未出局，暂时不可执行该操作！');
                exit();
            }

            if ( $info['can_replay'] == 0){
                $this->error('未达到出局条件，暂时不可执行复投操作！');
                exit();
            }
            $out = $fee_rs['str3'] + $fee_rs['str4'];


            if ( $info['agent_cf'] < $out){
                $this->error('金额不足，暂时不可执行该操作！');
                exit();
            }
            $up = $fck->execute("update __TABLE__ set agent_cf=agent_cf-".$out.",agent_cash=agent_cash+".$fee_rs['str3'].",agent_use=agent_use+".$fee_rs['str4']." where id=".$id);
            if ($up){
                $res = $fck->create_info_fck2($id,2);
                if ($res){
                    $fck->where('id='.$id)->setField('can_replay',0);
                    $this->success('复投成功！');
                }
            }

        }else{
            $this->error('登陆已超时！请重新登陆');
        }
    }


    public function reg_new_user(){
        $fck=M('fck');

        $rid=$keyArray[1];
        $mapp  = array();
        $mapp['id'] = $rid;


        $authInfoo = $fck->where($mapp)->find();
        $name= $authInfoo['user_id'];

        $find_appid=$fck->where("appid='".$fromUsername."'")->find();

        if(!$find_appid) {

            create_user:
            $mynn = '' . rand(1000000, 9999999);

            $fwhere['user_id'] = $mynn;
            $frss = $fck->where($fwhere)->field('id')->find();
            if ($frss) {
                goto create_user;
            } else {
                $user_id = $mynn;
            }

            $app_id = $fromUsername;
            $data = array();
            $data['user_id'] = $mynn;
            $data['appid'] = $app_id;
            $data['re_path'] = $authInfoo['re_path'] . $authInfoo['id'] . ',';  //推荐路径
            $data['re_id'] = $authInfoo['id'];                              //推荐人ID
            $data['re_name'] = $authInfoo['user_id'];
            $data['u_level'] = 0;
            $data['pdt'] = $time;
            $data['is_pay'] = 1;
            $data['re_level'] = $authInfoo['re_level'] + 1;                 //代数(绝对层数)

            $password = 1;
            $password2 = 2;
            $data['password'] = md5($password);  //一级密码加密
            $data['passopen'] = md5($password2);  //二级密码加密
            $data['pwd1'] = $password;       //一级密码不加密
            $data['pwd2'] = $password2;       //二级密码不加密
            //                $ans = $fck->add($data);
            $ans = $fck->execute("insert into __TABLE__ (re_name,re_path,re_id,pdt,u_level,user_id,is_pay,re_level,appid,password,passopen,pwd1,pwd2) values ('" . $data['re_name'] . "','" . $data['re_path'] . "'," . $data['re_id'] . "," . $time . ",1,'" . $mynn . "',1," . $data['re_level'] . ",'" . $app_id . "','" . $data['password'] . "','" . $data['passopen'] . "',1,2)");

            //                $fck->execute('update __TABLE__ set re_nums=re_nums+1 where id='.$rid);

            //                if ($ans){
            $msgType = "text";

            $contentStr = '欢迎您关注微利商行，您的推荐人是 ' . $name . '! 您可以使用账户：' . $user_id . ' 密码：' . $password . ' 二级密码：' . $password2 . ' 来登陆微利商行系统！';

            $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
            echo $resultStr;
        }
    }

    public function k_line(){
        $fh_point = M('fh_point');

        $last = $fh_point->order('id desc')->find();
        $start = $last['fh_time'] - 7*24*3600;
        $res = $fh_point->where('fh_time >'.$start.' and fh_time<='.$last['fh_time'])->order('id asc')->limit(7)->select();

        foreach ($res as $key => $value) {
            $kds.=$value['money'];
            if($value['money']){

                $kds.=',';
            }

            $data.=$value['td_time'];
            if($value['td_time']){

                $data.=',';
            }
        }
        $kdss=rtrim($kds,',');
        $datas = rtrim($data,',');

        $this->assign('res', $kdss);
        $this->assign('data', $datas);
        $this->display();
    }

    public function downloadInstall_android(){
        vendor("phpqrcode.phpqrcode");
        $see = $_SERVER['HTTP_HOST'].__ROOT__;
        $see = str_replace("//","/",$see);
        $data ="http://$see/Public/Uploads/package/android.apk";
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 3;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false

        // 生成的文件名
        ob_end_clean();//清空缓冲区
        QRcode::png($data, $false, $level, $size);
    }
    public function downloadInstall_apple(){
        vendor("phpqrcode.phpqrcode");
        $see = $_SERVER['HTTP_HOST'].__ROOT__;
        $see = str_replace("//","/",$see);
        $data ="http://fir.im/zhiqiao";
        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 3;
        // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false

        // 生成的文件名
        ob_end_clean();//清空缓冲区
        QRcode::png($data, $false, $level, $size);
    }


    public function test() {
        $data = [];
        $data['money'] = 1;
        $data['amount'] = 2;
        $data['x_date'] = time();
        $data['is_lock'] = 1;

        M('xml')->add($data);
    }
}
?>